﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;

namespace news_crl
{
    public partial class Form1 : Form
    {
        int d_flag = 0; //DB연결 확인하는 플래그
        //int s_flag = 0; //서버 연결 확인하는 플래그
        DataBaseManage dbm;
        Thread thread;

        public Form1()
        {
            InitializeComponent();
            button2.Enabled = false;
            //처음에 켰을 때 서버 중지 버튼을 막아 둔다.
        }

        private void crwaler(){
            listBox1.Items.Add("크롤러 서버 시작 중...");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;

        }

        private void DB_check()
        {
            Boolean dbcheck;
            dbm = new DataBaseManage();
            listBox1.Items.Add("DB에 연결 하는 중...");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;

            dbcheck = dbm.testDB();

            if (dbcheck)
            {
                d_flag = 1;
            }

            listBox1.Items.Add("DB에 연결 완료...");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("크롤링을 시작 하겠습니다.");
            listBox1.Items.Add("서버를 시작하는 중...");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            Thread.Sleep(100);
            label3.Text = "서버 시작 중";
            label3.ForeColor = Color.Violet;
            label4.Text = "연결 확인 중";
            label4.ForeColor = Color.Violet;

            crwaler();
            DB_check();

            listBox1.Items.Add("#크롤러 서버 시작");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            label3.Text = "서버 작동";
            label3.ForeColor = Color.Green;
            if (d_flag == 1)
            {
                listBox1.Items.Add("#DB 정상 연결");
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                label4.Text = "연결 정상";
            }
            else { 
                MessageBox.Show("DB 연결이 되지 않습니다.\n 다시 한번 확인 하시기 바랍니다.");
                label4.Text = "연결 실패";
            }
            
            
            label4.ForeColor = Color.Green;
            button2.Enabled = true;
            button1.Enabled = false;

            ///////////////////////////////////////// 크롤링 시작//////////////////////////////////////
            thread = new Thread(new ThreadStart(crawlingStart));

            thread.Start();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            CheckBox[] cbSet = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6, checkBox7, checkBox8, checkBox9, checkBox10 };
            for (int i = 0; i < cbSet.Length; i++)
                cbSet[i].Checked = true;  // true이면 전체선택, false이면 전체 해제
        }

        private void button4_Click(object sender, EventArgs e)
        {
            CheckBox[] cbSet = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6, checkBox7, checkBox8, checkBox9, checkBox10 };
            for (int i = 0; i < cbSet.Length; i++)
                cbSet[i].Checked = false; 
        }

        private void button5_Click(object sender, EventArgs e)
        {
            MessageBox.Show("설정 되었습니다.");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("서버를 중지 하는 중..");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            listBox1.Items.Add("#중지 완료");

            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            label3.ForeColor = Color.Red;
            label3.Text = "작동 중지";
            label4.ForeColor = Color.Red;
            label4.Text = "연결 중지";
            button2.Enabled = false;
            button1.Enabled = true;

            thread.Abort();
        }

        ////////////////////////////////////////

        private void crawlingStart()
        {
            while (true)
            {
                DataBaseManage db = new DataBaseManage();

                db.openDB();
                String titleData = db.getTitle();
                db.closeDB();
                db.openDB();

                XmlDocument doc = new XmlDocument();
                doc.Load("http://rss.joinsmsn.com/joins_life_list.xml");

                XmlElement rss = doc.DocumentElement;
                XmlElement channel = rss.FirstChild as XmlElement;//<channel>

                //Channel의 자식 중 item이 블로그 내용의 집합

                int count = 0;

                foreach (XmlElement ele in channel.ChildNodes)
                {
                    //sourceBox.AppendText(ele.InnerText);
                    //블로그의 최신글 제목만을 출력 -> 아이템필터링
                    //특정 엘리먼트 검색 == xPath로 처리

                    if (ele.Name == "item")
                    {
                        //Console.WriteLine(title.InnerText);

                        XmlElement title = ele.ChildNodes[0] as XmlElement;

                        if (count == 0)
                        {
                            db.insertrecentlyDB(title.InnerText);
                            count++;
                        }

                        if (title.InnerText.Equals(titleData))
                        {
                            //MessageBox.Show(titleData);
                            break;
                        }

                        listBox1.Items.Add("추가 : " + title.InnerText);
                        listBox1.SelectedIndex = listBox1.Items.Count - 1;

                        //sourceBox.AppendText("제목\n");
                        //sourceBox.AppendText(title.InnerText);
                        //sourceBox.AppendText("\n\n");

                        /*
                        XmlElement desc = ele.ChildNodes[2] as XmlElement;
                        sourceBox.AppendText("본문\n");
                        sourceBox.AppendText(desc.InnerText);
                        sourceBox.AppendText("\n\n");
                        */

                        XmlElement link = ele.ChildNodes[1] as XmlElement;
                        String desc = GetStock(link.InnerText);
                        //sourceBox.AppendText("본문\n");
                        //sourceBox.AppendText(desc);
                        //sourceBox.AppendText("\n");

                        //sourceBox.AppendText("링크\n");
                        //sourceBox.AppendText(link.InnerText);
                        //sourceBox.AppendText("\n\n");


                        XmlElement d_time = ele.ChildNodes[4] as XmlElement;

                        String temp_Time = d_time.InnerText;
                        String[] split_Str = temp_Time.Split('T');

                        String day_Time = split_Str[0] + " ";
                        temp_Time = split_Str[1];
                        String[] split_Time = temp_Time.Split(':');
                        day_Time = day_Time + split_Time[0] + "시 " + split_Time[1] + "분";

                        //sourceBox.AppendText("작성일\n");
                        //sourceBox.AppendText(day_Time);
                        //sourceBox.AppendText("\n\n\n");

                        db.insertDB(title.InnerText, desc, day_Time, link.InnerText);
                    }
                }
                db.closeDB();

                Thread.Sleep(120000);
                //MessageBox.Show("실행");
            }

        }

        private String GetStock(String strURL)
        {
            //String strURL = "http://article.joinsmsn.com/news/article/article.asp?total_id=7743758&cloc=rss|news|society";
            String tempStr = GetHtmlString(strURL);
            String[] STock = new String[3];
            String[] SplitStr = tempStr.Split(':');
            //int count = 0;

            //return STock;
            //return tempStr;
            return SplitStr[74];
        }
        private String GetHtmlString(String url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String strHtml = reader.ReadToEnd();
            //strHtml = Regex.Replace(strHtml, @"<(.|\n)*?>", String.Empty);
            strHtml = Regex.Replace(strHtml, @"<(.|)*?>", String.Empty);
            //strHtml = strHtml.Replace(" ", "").Replace("\t", "").Replace("//-->", "");
            strHtml = strHtml.Replace("\t", "").Replace("//-->", "");
            String[] str = strHtml.Split(new Char[] { '\n' });
            strHtml = null;
            foreach (String s in str)
            {
                if (s.Trim() != "")
                    strHtml += s + ":";
            }
            reader.Close();
            response.Close();
            return strHtml;
        }

        /*
        private void button_newsData_Click(object sender, EventArgs e)
        {
            String strURL = "http://article.joinsmsn.com/news/article/article.asp?total_id=7731213&cloc=rss|news|society";
            sourceBox.Clear();
            String data = GetStock2(strURL);
            sourceBox.AppendText(data);
        }
        */

        private String GetStock2(String strURL)
        {
            //String strURL = "http://article.joinsmsn.com/news/article/article.asp?total_id=7731213&cloc=rss|news|society";
            String tempStr = GetHtmlString(strURL);
            String[] STock = new String[3];
            String[] SplitStr = tempStr.Split(':');

            //return STock;
            //return tempStr;
            return tempStr;
        }
    }

    public partial class crawling : Form1
    {
        public void first_crwal() {
            MessageBox.Show("안녕하지 못하다");
        }
    }
}
 